﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.BLL;
using KPIS.GERP.GIMS.IBLL;
using KPIS.GERP.GIMS.MODEL;
using System.Data;
using System.IO;
using KPIS.GERP.GIMS.APP.APP_CODE;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Purchase_Request : System.Web.UI.Page
    {
        Common.Main cn = new Common.Main();
        CommandControl cmdFac = new CommandControl();
        PurchaseRequestBLL bllPrReq = new PurchaseRequestBLL();
        IBLLMasterPurchaseMethod bllMasPcMethod = new MasterPurchaseMethodBLL();
        PurchaseRequestItemBLL bllPcReqItem = new PurchaseRequestItemBLL();
        IBLLHrmEmployee bllEmployee = new HrmEmployeeBLL();
        private const int ItemsPerRequest = 10;
        private const int GridWidth = 150;
        double totalPrice = 0;
        //double totalOriginalPriceMin = 0;
        double totalOriginalPriceMax = 0;
        int nCount = 0;
        double sumValue = 0;
        IBLLDocument bllPprFile = new DocumentBLL();
        IBLLSysDurationCount bllDurationCount = new SysDurationCountBLL();
        IBLLSysDurationType bllDurationType = new SysDurationTypeBLL();
        private bool isItemInEditMode = false;
        PurchaseRequestCommitteeBLL bllPrCommittee = new PurchaseRequestCommitteeBLL();
        IBLLMasterCommitteeFunction bllComFunction = new MasterCommitteeFunctionBLL();
        IBLLMasterCommitteePosition bllComPosition = new MasterCommitteePositionBLL();
        BidderBLL bllBidder = new BidderBLL();
        PrePurchaseRequestInfo info = new PrePurchaseRequestInfo();
        BidderQuotationBLL bllBidderQuo = new BidderQuotationBLL();
        SysReportBLL bllReport = new SysReportBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadDurationType();
                LoadDurationCount();
                LoadCommitteePosition();
                LoadCommitteeFunction();

                GetKeyValue();
                rdbDuration.Attributes.Add("onclick", "return ChangeDurationRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");
                rdbDate.Attributes.Add("onclick", "return ChangeDateRequire('" + panelDuration.ClientID + "','" + panelDateReq.ClientID + "','" + panelDateReqPick.ClientID + "')");

                TipConfirm.TargetControls.Add(Forward.ClientID, true);
                TipConfirmBid.TargetControls.Add(ForwardBid.ClientID, true);
                TipHistory.TargetControls.Add(History_File.ClientID, "1", true);

                int seq = GetSeq();
                Button TmpBtn = (Button)RadPanelBar1.FindItemByValue("Bar1").FindControl("btnHistoryApprove");
                this.TipHistoryApprove.TargetControls.Add(TmpBtn.ClientID, "HisApprove:" + seq, true);

                TmpBtn = (Button)RadPanelBar1.FindItemByValue("Bar1").FindControl("btnHistoryInform");
                this.TipHistoryInform.TargetControls.Add(TmpBtn.ClientID, "HisInform:" + seq, true);

                hdSeq.Value = seq.ToString();
            }

            if (rdbDate.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:hidden");
                panelDateReq.Attributes.Add("style", "visibility:visible");
                panelDateReqPick.Attributes.Add("style", "visibility:visible");
            }
            if (rdbDuration.Checked)
            {
                panelDuration.Attributes.Add("style", "visibility:visible");
                panelDateReq.Attributes.Add("style", "visibility:hidden");
                panelDateReqPick.Attributes.Add("style", "visibility:hidden");
            }

            if (RadTabStrip1.SelectedTab.Value == "Select")
            {
                LoadGridSelect();
            }
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (RadTabStrip1.SelectedTab.Value == "Detail")
            {
                GetKeyValue();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Item")
            {
                this.IsItemInEditMode = false;
                LoadGridItem();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Committee")
            {
                LoadGridCommittee();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Seller")
            {
                LoadGridSeller();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Judgement")
            {
                LoadJudgement();
                LoadGridJudgement();
            }
            else if (RadTabStrip1.SelectedTab.Value == "File")
            {
                LoadGridFile();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Report")
            {
                LoadGrid_Report();
            }
            else if (RadTabStrip1.SelectedTab.Value == "Progress")
            {
                LoadGridApprove();
                LoadGridInform();
                LoadGridRequest();
                LoadGridPublishing();
                LoadGridCommand();
                LoadGridCheck();
            }
            //else if (RadTabStrip1.SelectedTab.Value == "Select")
            //{
            //    LoadGridSelect();
            //}
        }

        protected void OnAjaxUpdate(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip(args.Value, args.UpdatePanel);
        }

        protected void OnAjaxUpdateBid(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTipBid(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Request_Confirm.ascx");
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm)ctrl).RefreshParentDisplay = new CallBackHandle(RefreshDisplay);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm)ctrl).GetPrSeq = new CallBackHandleReturnInt(GetSeq);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm)ctrl).Alert = new CallBackHandleAlert(Alert);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        private void UpdateToolTipBid(string elementID, UpdatePanel panel)
        {
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Request_Confirm_Bid.ascx");
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm_Bid)ctrl).RefreshParentDisplay= new CallBackHandle(RefreshDisplay);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm_Bid)ctrl).GetPrSeq = new CallBackHandleReturnInt(GetSeq);
            ((KPIS.GERP.GIMS.APP.APP_UI.UserControl.TIP_Purchase_Request_Confirm_Bid)ctrl).Alert = new CallBackHandleAlert(Alert);
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void ManageDisplay(string Status, string bid_status)
        {
            switch (Status)
            {
                case "A":
                case "P":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = false;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = false;
                    // tab รายชื่อคณะกรรมการ
                    panelCommand_Seller.Visible = false;
                    // tab ผู้ขาย/รับจ้าง
                    panelCommand_Committee.Visible = false;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = false;
                    Forward.Visible = false;
                    ForwardBid.Visible = false;
                    Reject.Visible = true;
                    break;
                case "C":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = false;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = false;
                    // tab รายชื่อคณะกรรมการ
                    panelCommand_Seller.Visible = false;
                    // tab ผู้ขาย/รับจ้าง
                    panelCommand_Committee.Visible = false;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = false;
                    Forward.Visible = false;
                    ForwardBid.Visible = false;
                    Reject.Visible = false;
                    break;
                case "N":
                case "R":
                case "W":
                    // tab ข้อมูลหลัก
                    panelCommand_Detail.Visible = true;
                    // tab รายการพัสดุ
                    panelCommand_Item.Visible = true;
                    // tab รายชื่อคณะกรรมการ
                    panelCommand_Seller.Visible = true;
                    // tab ผู้ขาย/รับจ้าง
                    panelCommand_Committee.Visible = true;
                    // tab เอกสารแนบ
                    panelCommand_File.Visible = true;
                    Reject.Visible = false;
                    if (bid_status == "C")
                    {
                        Forward.Visible = true;
                        ForwardBid.Visible = false;
                    }
                    else
                    {
                        Forward.Visible = false;
                        ForwardBid.Visible = true;
                    }
                    break;
            }
        }

        protected void RadManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            string[] TmpArgument = e.Argument.Split(':');

            if (TmpArgument[0] == "SeqCommitteeClick")
            {
                LoadEditCommittee(Convert.ToInt32(TmpArgument[1]));
            }
            if (TmpArgument[0] == "CloseWindow")
            {
                LoadGridSeller();
            }
            if (TmpArgument[0] == "ReportPdfClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetSeq() + "','pdf');");
            }
            if (TmpArgument[0] == "ReportWordClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetSeq() + "','word');");
            }
            if (TmpArgument[0] == "ReportExcelClick")
            {
                RadManager1.ResponseScripts.Add(@"OpenReport('" + TmpArgument[1] + "','" + GetSeq() + "','excel');");
            }
        }

        protected void RefreshDisplay()
        {
            RadManager1.ResponseScripts.Add(@"CloseActiveToolTip();");
            GetKeyValue();
        }

        protected int GetSeq()
        {
            int seq = Convert.ToInt32(Request.QueryString["Seq"]);
            return seq;
        }

        protected void Alert()
        {
            RadManager1.Alert(Session["Alert"].ToString());
        }

        //-----------------------------------------------------------------------------------------------

        #region tab ข้อมูลหลัก

        protected void LoadPurchaseMethod()
        {
            int seq = GetSeq();
            IList<MasterPurchaseMethodInfo> infPprMethod = bllMasPcMethod.GetMasterPurchaseMethodByPrSeq(seq);
            cbPurchaseMethod.DataSource = infPprMethod;
            cbPurchaseMethod.DataBind();
        }

        protected void LoadDurationType()
        {
            IList<SysDurationTypeInfo> infoList = bllDurationType.GetSysDurationType();
            cbDurationType.DataSource = infoList;
            cbDurationType.DataBind();
        }

        protected void LoadDurationCount()
        {
            IList<SysDurationCountInfo> infoList = bllDurationCount.GetSysDurationCount();
            cbDurationCount.DataSource = infoList;
            cbDurationCount.DataBind();
        }

        protected void GetKeyValue()
        {
            PurchaseRequestInfo infoPrReq = new PurchaseRequestInfo();
            int seq = GetSeq();
            infoPrReq = bllPrReq.GetPurchaseRequest(seq);
            
            /*------------------ add data to text --------------------------*/

            lblYearType.Text = infoPrReq.InfoYearType.Name + " : ";
            lblYear.Text = infoPrReq.BgmYear.ToString();
            lblPurchaseRule.Text = infoPrReq.InfoPurchaseRule.Name;
            lblPurchaseType.Text = infoPrReq.InfoPurchaseType.Name;
            lblPurchaseMethod.Text = infoPrReq.InfoPurchaseMethod.Name;

            if (infoPrReq.RequireDuration != null)
            {
                lblDuration.Text = "ภายใน " + infoPrReq.RequireDuration + " " + infoPrReq.InfoDurationType.Name + " นับจาก " + infoPrReq.InfoDurationCount.Name;
            }
            else if (infoPrReq.RequireDate != null)
            {
                lblDuration.Text = "ภายในวันที่ " + ((DateTime)infoPrReq.RequireDate).ToString("dd/MM/yyyy"); ;
            }
            else
            {
                lblDuration.Text = "";
            }

            txtDate.Text = ((DateTime)infoPrReq.PurchaseDate).ToString("dd/MM/yyyy");
            txtName.Text = infoPrReq.Name;
            txtReason.Text = infoPrReq.Reason;
            txtRemark.Text = infoPrReq.Remark;
            cbPurchaseMethod.Text = infoPrReq.InfoPurchaseMethod.Name;
            cbPurchaseMethod.SelectedValue = infoPrReq.InfoPurchaseMethod.Seq.ToString() + ":" + infoPrReq.InfoPurchaseMethod.Bidding_status;
            txtPurchaseMethodReason.Text = infoPrReq.MethodReason;
            if (infoPrReq.RequireDuration != null)
            {
                rdbDuration.Checked = true;
                rdbDate.Checked = false;
                txtDurationReq.Text = infoPrReq.RequireDuration.ToString();
                cbDurationType.SelectedValue = infoPrReq.InfoDurationType.Seq.ToString();
                cbDurationCount.SelectedValue = infoPrReq.InfoDurationCount.Seq.ToString();
            }
            else if (infoPrReq.RequireDate != null)
            {
                rdbDate.Checked = true;
                rdbDuration.Checked = false;
                txtDateReq.Text = ((DateTime)infoPrReq.RequireDate).ToString("dd/MM/yyyy");
            }

            if (infoPrReq.RequireDate == null & infoPrReq.RequireDuration == null)
            {
                rdbDuration.Checked = true;
                rdbDate.Checked = false;
            }

            lblStatus.Text = infoPrReq.InfoRecordStatus.Name;
            lblProgress.Text = infoPrReq.InfoProgress.Name;

            /*------------------- show and hide text --------------------*/
            cmdFac.ViewCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetViewMode(panelDateReqPick);
            cmdFac.SetPanelList(panelDateReqPick, "View");
            cmdFac.SetViewMode(panelDateReq);
            cmdFac.SetPanelList(panelDateReq, "View");
            cmdFac.SetViewMode(panelDuration);
            cmdFac.SetPanelList(panelDuration, "View");

            /*---------------------- show and hide Header ----------------*/
            if (infoPrReq.InfoPurchaseMethod.Seq == null)
            {
                panelWarning.Visible = true;
                panelHidden.Visible = false;
            }
            else
            {
                panelWarning.Visible = false;
                panelHidden.Visible = true;
            }

            ManageDisplay(infoPrReq.InfoRecordStatus.Status, infoPrReq.InfoPurchaseMethod.Bidding_status);
            RefreshTab(infoPrReq.InfoPurchaseMethod.Bidding_status);
            RadTabStrip1.Tabs[7].Visible = (infoPrReq.InfoPurchaseMethod.Name.Length > 0);
        }

        protected void Edit_Detail_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Detail, panelGrid_Detail, panelCommand_Detail);
            cmdFac.SetPanelList(panelDateReqPick, "Edit");
            cmdFac.SetPanelList(panelDateReq, "Edit");
            cmdFac.SetPanelList(panelDuration, "Edit");
            lblYearType.Visible = true;
            lblYear.Visible = true;
            lblPurchaseRule.Visible = true;
            lblPurchaseType.Visible = true;
            LoadValiDateDetail();
        }

        protected void EditSave_Detail_Click(object sender, EventArgs e)
        {
            PurchaseRequestInfo info = new PurchaseRequestInfo();
            MasterPurchaseMethodInfo infoMethod = new MasterPurchaseMethodInfo();
            SysDurationTypeInfo infoDurType = new SysDurationTypeInfo();
            SysDurationCountInfo infoDurCount = new SysDurationCountInfo();
            info.Seq = GetSeq();
            info.PurchaseDate = Convert.ToDateTime(txtDate.TextWithLiterals);
            info.Name = txtName.Text;
            info.Reason = txtReason.Text;
            info.Remark = txtRemark.Text;
            string[] pcMethodStr = cbPurchaseMethod.SelectedValue.ToString().Split(':');
            infoMethod.Seq = Convert.ToInt32(pcMethodStr[0]);
            info.MethodReason = txtPurchaseMethodReason.Text;
            if (rdbDuration.Checked)
            {
                if (txtDurationReq.Text.Length > 0)
                {
                    info.RequireDuration = Convert.ToInt32(txtDurationReq.Text);
                    infoDurType.Seq = Convert.ToInt32(cbDurationType.SelectedValue.ToString());
                    infoDurCount.Seq = Convert.ToInt32(cbDurationCount.SelectedValue.ToString());
                }
            }
            else if (rdbDate.Checked)
            {
                if (txtDateReq.Text.Length > 0)
                {
                    info.RequireDate = Convert.ToDateTime(txtDateReq.TextWithLiterals);
                }
            }

            info.InfoPurchaseMethod = infoMethod;
            info.InfoDurationType = infoDurType;
            info.InfoDurationCount = infoDurCount;

            try
            {
                bllPrReq.UpdatePurchaseRequest(info);
                GetKeyValue();
                panelWarning.Visible = false;
                panelHidden.Visible = true;
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Cancel_Detail_Click(object sender, EventArgs e)
        {
            GetKeyValue();
        }

        protected void btnEditPcMethod_Click(object sender, EventArgs e)
        {
            RadTabStrip1.SelectedIndex = 0;
            RadPageView1.Selected = true;
            Edit_Detail_Click(null, null);
        }

        protected void RefreshTab(string Status)
        {
            if (Status == SystemInfo._CancelRecordStatus) //ไม่ประกาศ
            {
                RadTabStrip1.Tabs[3].Visible = true;
                RadTabStrip1.Tabs[4].Visible = true;
                RadTabStrip1.Tabs[5].Visible = true;
            }
            else
            {
                RadTabStrip1.Tabs[3].Visible = false;
                RadTabStrip1.Tabs[4].Visible = false;
                RadTabStrip1.Tabs[5].Visible = false;
            }
        }

        protected void cbPurchaseMethod_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            int seq = GetSeq();
            IList<MasterPurchaseMethodInfo> infoList = bllMasPcMethod.GetMasterPurchaseMethodByPrSeq(seq);
            for (int i = 0; i < infoList.Count; i++)
            {
                cbPurchaseMethod.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString() + ":" + infoList[i].Bidding_status + ":" + infoList[i].Descr));
            }
            cbPurchaseMethod.DataBind();
        }

        private void LoadValiDateDetail()
        {
            RequiredFieldValidator valDate = new RequiredFieldValidator();
            valDate.ID = "ValtxtDate";
            valDate.ControlToValidate = "txtDate";
            valDate.SetFocusOnError = true;
            valDate.Display = ValidatorDisplay.Dynamic;
            valDate.ErrorMessage = "* กรุณาระบุวันที่รายการ *";
            panelValDate.Controls.Add(valDate);
            CustomValidator valCustomDate = new CustomValidator();
            valCustomDate.ID = "ValCustomDate";
            valCustomDate.ControlToValidate = "txtDate";
            valCustomDate.SetFocusOnError = true;
            valCustomDate.Display = ValidatorDisplay.Dynamic;
            valCustomDate.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDate.ClientValidationFunction = "validateDate";
            panelValDate.Controls.Add(valCustomDate);
            RequiredFieldValidator valName = new RequiredFieldValidator();
            valName.ID = "ValtxtName";
            valName.ControlToValidate = "txtName";
            valName.SetFocusOnError = true;
            valName.Display = ValidatorDisplay.Dynamic;
            valName.ErrorMessage = "* กรุณาระบุเรื่อง *";
            panelValName.Controls.Add(valName);
            CustomValidator valCustomDateReq = new CustomValidator();
            valCustomDateReq.ID = "ValCustomDateReq";
            valCustomDateReq.ControlToValidate = "txtDateReq";
            valCustomDateReq.SetFocusOnError = true;
            valCustomDateReq.Display = ValidatorDisplay.Dynamic;
            valCustomDateReq.ErrorMessage = "* กรุณาระบุวันที่ให้ถูกต้อง *";
            valCustomDateReq.ClientValidationFunction = "validateDate";
            panelValDateReq.Controls.Add(valCustomDateReq);
            RequiredFieldValidator valcbPurchaseMethod = new RequiredFieldValidator();
            valcbPurchaseMethod.ID = "ValcbPurchaseMethod";
            valcbPurchaseMethod.ControlToValidate = "cbPurchaseMethod";
            valcbPurchaseMethod.SetFocusOnError = true;
            valcbPurchaseMethod.Display = ValidatorDisplay.Dynamic;
            valcbPurchaseMethod.ErrorMessage = "* กรุณาระบุวิธีการจัดหา *";
            panelValcbPurchaseMethod.Controls.Add(valcbPurchaseMethod);
            RequiredFieldValidator valPurchaseMethodReason = new RequiredFieldValidator();
            valPurchaseMethodReason.ID = "ValtxtPurchaseMethodReason";
            valPurchaseMethodReason.ControlToValidate = "txtPurchaseMethodReason";
            valPurchaseMethodReason.SetFocusOnError = true;
            valPurchaseMethodReason.Display = ValidatorDisplay.Dynamic;
            valPurchaseMethodReason.ErrorMessage = "* กรุณาระบุเหตุผลที่เลือกใช้วิธีการ *";
            panelValPurchaseMethodReason.Controls.Add(valPurchaseMethodReason);
        }

        #endregion 

        //-----------------------------------------------------------------------------------------------

        #region tab รายการพัสดุ

        protected void LoadGridItem()
        {
            int seq = GetSeq();
            IList<PurchaseRequestItemInfo> infoPcReqItem = bllPcReqItem.GetPurchaseRequestItem_EditPcReq(seq);
            Grid_Item.DataSource = infoPcReqItem;
            Grid_Item.MasterTableView.GroupByExpressions.Clear();
            GridGroupByExpression geExpense = new GridGroupByExpression(Grid_Item.Columns[0]);
            Grid_Item.MasterTableView.GroupByExpressions.Add(geExpense);
            Grid_Item.DataBind();
        }

        protected void Grid_Item_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridItem();
        }

        protected void Grid_Item_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (nCount == 0)
            {
                totalPrice = 0;
                //totalOriginalPriceMin = 0;
                totalOriginalPriceMax = 0;
            }
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                nCount++;
                double qty = 0;
                double price = 0;
                double Txtqty = 0;
                double Txtprice = 0;
                double oriQty = 0;
                //double oriPriceMin = 0;
                double oriPriceMax= 0;
                GridDataItem dataBoundItem = e.Item as GridDataItem;

                if (((Label)(dataBoundItem["Qty"].FindControl("lblQty"))).Text.Length > 0)
                {
                    qty = double.Parse(((Label)(dataBoundItem["Qty"].FindControl("lblQty"))).Text);
                }
                if (((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text.Length > 0)
                {
                    price = double.Parse(((Label)(dataBoundItem["Price"].FindControl("lblPrice"))).Text);
                }

                if (dataBoundItem["OriginalQty"].Text.Length > 0)
                {
                    oriQty = double.Parse(dataBoundItem["OriginalQty"].Text);
                }
                //if (dataBoundItem["MinPrice"].Text.Length > 0)
                //{
                //    oriPriceMin = double.Parse(dataBoundItem["MinPrice"].Text);
                //}
                if (dataBoundItem["MaxPrice"].Text.Length > 0)
                {
                    oriPriceMax = double.Parse(dataBoundItem["MaxPrice"].Text);
                }

                RadNumericTextBox txtPrice = ((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice")));
                RadNumericTextBox txtQty = ((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty")));

                txtPrice.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onFocus", "return Focus('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtPrice.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");
                txtQty.Attributes.Add("onBlur", "return Blur('" + txtPrice.ClientID + "','" + txtQty.ClientID + "')");

                if (((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString().Length > 0)
                {
                    Txtqty = double.Parse(((RadNumericTextBox)(dataBoundItem["Qty"].FindControl("txtQty"))).Value.ToString());
                }
                if (((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString().Length > 0)
                {
                    Txtprice = double.Parse(((RadNumericTextBox)(dataBoundItem["Price"].FindControl("txtPrice"))).Value.ToString());
                }

                totalPrice += (qty * price);
                totalOriginalPriceMax += (oriQty * oriPriceMax);
                sumValue += (qty * price);
            }
            else if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["Descr"].Controls.Add(new LiteralControl("<div align='right' style='color: Black; font-weight: bold;'>วงเงินจัดหาทั้งหมด :</div> "));
                ((Label)footer["OriginalPrice"].FindControl("lblTotalOriginalPrice")).Text = totalOriginalPriceMax.ToString("###,###,##0.00");
                if (this.IsItemInEditMode)
                    ((RadNumericTextBox)footer["Price"].FindControl("txtTotalPrice")).Value = Double.Parse(sumValue.ToString());
                else
                    ((Label)footer["Price"].FindControl("lblTotalPrice")).Text = totalPrice.ToString("###,###,##0.00");
                nCount = 0;
            }
        }

        protected void Edit_Item_Click(object sender, EventArgs e)
        {
            Edit_Item.Visible = false;
            EditSave_Item.Visible = true;
            Cancel_Item.Visible = true;

            this.IsItemInEditMode = true;
            LoadGridItem();
        }

        protected void EditSave_Item_Click(object sender, EventArgs e)
        {
            try
            {
                IList<PurchaseRequestItemInfo> infoList = new List<PurchaseRequestItemInfo>();

                foreach (GridDataItem data in Grid_Item.MasterTableView.Items)
                {
                    PurchaseRequestItemInfo info = new PurchaseRequestItemInfo();
                    info.Seq = Convert.ToInt32(data["Seq"].Text.Replace("&nbsp;", ""));
                    info.Descr = ((TextBox)data["Descr"].FindControl("txtDescr")).Text;
                    if (((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Value.ToString() != "")
                    {
                        info.Qty = Convert.ToInt32(((RadNumericTextBox)data["Qty"].FindControl("txtQty")).Value);
                    }
                    else
                    {
                        RadManager1.Alert("กรุณาระบุจำนวนซื้อจากพัสดุให้ครบถ้วน");
                        ReCalculateAmount();
                        return;
                    }
                    if (((RadNumericTextBox)data["Price"].FindControl("txtPrice")).Value.ToString() != "")
                    {
                        info.Price = Convert.ToDouble(((RadNumericTextBox)data["Price"].FindControl("txtPrice")).Value);
                    }
                    else
                    {
                        RadManager1.Alert("กรุณาระบุราคาต่อหน่วยจากพัสดุให้ครบถ้วน");
                        ReCalculateAmount();
                        return;
                    }
                    infoList.Add(info);
                }

                bllPcReqItem.Update(infoList);

                Edit_Item.Visible = true;
                EditSave_Item.Visible = false;
                Cancel_Item.Visible = false;

                this.IsItemInEditMode = false;
                LoadGridItem();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void ReCalculateAmount()
        {
            double sumPrice = 0;
            double price = 0;
            double qty = 0;
            foreach (GridDataItem data in Grid_Item.MasterTableView.Items)
            {
                RadNumericTextBox txtPrice = ((RadNumericTextBox)(data["Price"].FindControl("txtPrice")));
                RadNumericTextBox txtQty = ((RadNumericTextBox)(data["Qty"].FindControl("txtQty")));
                price = (txtPrice.Text.Length > 0 ? Convert.ToDouble(txtPrice.Text) : 0);
                qty = (txtQty.Text.Length > 0 ? Convert.ToInt32(txtQty.Text) : 0);
                sumPrice += Convert.ToDouble(price) * Convert.ToDouble(qty);
            }

            GridFooterItem footer = (GridFooterItem)Grid_Item.MasterTableView.GetItems(GridItemType.Footer)[0];
            ((RadNumericTextBox)footer["Price"].FindControl("txtTotalPrice")).Value = Double.Parse(sumPrice.ToString());
        }

        protected void Cancel_Item_Click(object sender, EventArgs e)
        {
            Edit_Item.Visible = true;
            EditSave_Item.Visible = false;
            Cancel_Item.Visible = false;

            this.IsItemInEditMode = false;
            LoadGridItem();
        }

        protected bool IsItemInEditMode
        {
            get { return this.isItemInEditMode; }
            set { this.isItemInEditMode = value; }
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab คณะกรรมการ

        protected void LoadGridCommittee()
        {
            int seq = GetSeq();
            Grid_Committee.DataSource = bllPrCommittee.GetPurchaseRequestCommitteeWithParent(seq);
            GridGroupByExpression geFunction = new GridGroupByExpression(Grid_Committee.Columns[2]);
            GridGroupByExpression geRefNo = new GridGroupByExpression(Grid_Committee.Columns[3]);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geFunction);
            Grid_Committee.MasterTableView.GroupByExpressions.Add(geRefNo);
            Grid_Committee.DataBind();
            cmdFac.GridCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
        }

        protected void LoadCommitteePosition()
        {
            IList<MasterCommitteePositionInfo> infoList = bllComPosition.GetMasterCommitteePosition();
            cbCommitteePosition.DataSource = infoList;
            cbCommitteePosition.DataBind();
        }

        protected void LoadCommitteeFunction()
        {
            IList<MasterCommitteeFunctionInfo> infoList = bllComFunction.GetMasterCommitteeFunction();
            cbCommitteeFunction.DataSource = infoList;
            cbCommitteeFunction.DataBind();
        }

        protected void Grid_Committee_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommittee();
        }

        protected void rblCommitteeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            panelInternal.Visible = (rblCommitteeType.SelectedValue == "1");
            panelExternal.Visible = (rblCommitteeType.SelectedValue == "2");
            LoadValidateCommittee();
        }

        protected void cbCommitteeInternalName_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<HrmEmployeeInfo> infoList = bllEmployee.GetHrmEmployee(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cbCommitteeInternalName.Items.Add(new RadComboBoxItem(infoList[i].Name, infoList[i].Seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdJobSite = new TableCell();
                Label lblJobSite = new Label();
                lblJobSite.Text = infoList[i].InfoJobSite.Name;
                tdJobSite.Width = Unit.Pixel(200);
                tdJobSite.Controls.Add(lblJobSite);
                tr.Cells.Add(tdJobSite);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].Name;
                tdName.Width = Unit.Pixel(150);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdPosition = new TableCell();
                Label lblPosition = new Label();
                lblPosition.Text = infoList[i].InfoPosition.Name;
                tdPosition.Width = Unit.Pixel(150);
                tdPosition.Controls.Add(lblPosition);
                tr.Cells.Add(tdPosition);
                TableCell tdClass = new TableCell();
                Label lblClass = new Label();
                lblClass.Text = infoList[i].InfoClass.Name;
                tdClass.Width = Unit.Pixel(190);
                tdClass.Controls.Add(lblClass);
                tr.Cells.Add(tdClass);
                ((Table)cbCommitteeInternalName.Items[j].FindControl("tableCommmitteeInternalName")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void OnAjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            RadAjaxPanel1.Controls.Add(Page.LoadControl("../UserControl/TIP_Purchase_Request_Committee_History.ascx"));
        }

        protected void ShowGrid_Committee_Click(object sender, EventArgs e)
        {
            LoadGridCommittee();
        }

        protected void Edit_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            cmdFac.SetPanelList(panelInternal, "Edit");
            cmdFac.SetPanelList(panelExternal, "Edit");
        }

        protected void AddNew_Committee_Click(object sender, EventArgs e)
        {
            cmdFac.AddNewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            LoadValidateCommittee();
        }

        protected void btnDelete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestCommitteeInfo> infoList = new List<PurchaseRequestCommitteeInfo>();
            if (panelGrid_Committee.Visible)
            {
                foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
                {
                    PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
                    RecordInfo infoRecord = new RecordInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    info.DeleteReason = txtDeleteReason.Text;
                    infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                    infoRecord.Updated_when = DateTime.Now;
                    info.InfoRecord = infoRecord;
                    infoList.Add(info);
                }
            }
            else
            {
                PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
                info.DeleteReason = txtDeleteReason.Text;
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPrCommittee.DeleteAll(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridCommittee();
        }

        protected void Delete_Committee_Click(object sender, EventArgs e)
        {
            IList<PurchaseRequestCommitteeInfo> infoList = new List<PurchaseRequestCommitteeInfo>();
            if (panelGrid_Committee.Visible)
            {
                foreach (GridDataItem data in Grid_Committee.MasterTableView.GetSelectedItems())
                {
                    PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
                    info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                    infoList.Add(info);
                }
            }
            else
            {
                PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
                info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPrCommittee.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridCommittee();
        }

        protected void AddNewSave_Committee_Click(object sender, EventArgs e)
        {
            int seq = GetSeq();
            IList<PurchaseRequestCommitteeInfo> infoTempCommittee = new List<PurchaseRequestCommitteeInfo>();

            PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //บุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
            }
            infoRecord.Created_by = cn.UserID;
            infoRecord.Created_when = DateTime.Now;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            info.InfoRecord = infoRecord;
            infoTempCommittee.Add(info);

            try
            {
                bllPrCommittee.Insert(infoTempCommittee, seq);
                ClearCommittee();
                LoadGridCommittee();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void EditSave_Committee_Click(object sender, EventArgs e)
        {
            PurchaseRequestCommitteeInfo info = new PurchaseRequestCommitteeInfo();
            HrmEmployeeInfo infoEmployee = new HrmEmployeeInfo();
            MasterCommitteePositionInfo infoPosition = new MasterCommitteePositionInfo();
            MasterCommitteeFunctionInfo infoFunction = new MasterCommitteeFunctionInfo();
            HrmEmployeeInfo infoEmployeeDetail = new HrmEmployeeInfo();
            RecordInfo infoRecord = new RecordInfo();
            SysCommitteeTypeInfo infoType = new SysCommitteeTypeInfo();
            info.Seq = Convert.ToInt32(hdCommitteeSeq.Value);
            info.Ref_no = Convert.ToInt32(txtCommitteeRefno.Value);
            infoType.Seq = Convert.ToInt32(rblCommitteeType.SelectedValue);
            infoType.Name = (rblCommitteeType.SelectedItem.Text);
            infoPosition.Seq = Convert.ToInt32(cbCommitteePosition.SelectedValue);
            infoPosition.Name = cbCommitteePosition.SelectedItem.Text;
            infoFunction.Seq = Convert.ToInt32(cbCommitteeFunction.SelectedValue);
            infoFunction.Name = cbCommitteeFunction.SelectedItem.Text;
            if (infoType.Seq == 1) //บุคลากรภายใน
            {
                infoEmployee.Seq = Convert.ToInt32(cbCommitteeInternalName.SelectedValue);
            }
            else
            {
                info.Ex_name = txtCommitteeExternalName.Text;
                info.Ex_descr = txtCommitteeExternalDescr.Text;
            }
            infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Updated_when = DateTime.Now;
            info.InfoType = infoType;
            info.InfoExployee = infoEmployee;
            info.InfoPosition = infoPosition;
            info.InfoFunction = infoFunction;
            info.InfoRecord = infoRecord;
            try
            {
                bllPrCommittee.Update(info);
                LoadGridCommittee();
                ClearCommittee();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Cancel_Committee_Click(object sender, EventArgs e)
        {
            LoadEditCommittee(Convert.ToInt32(hdCommitteeSeq.Value));
        }

        protected void ClearCommittee()
        {
            txtCommitteeRefno.Text = "";
            rblCommitteeType.Items[0].Selected = true;
            rblCommitteeType.Items[1].Selected = false;
            panelInternal.Visible = true;
            panelExternal.Visible = false;
            cbCommitteeInternalName.SelectedIndex = -1;
            cbCommitteeInternalName.Text = "";
            txtCommitteeExternalName.Text = "";
            txtCommitteeExternalDescr.Text = "";
            cbCommitteePosition.SelectedIndex = -1;
            cbCommitteePosition.Text = "";
            cbCommitteeFunction.SelectedIndex = -1;
            cbCommitteeFunction.Text = "";
        }

        protected void LoadEditCommittee(int ComSeq)
        {
            PurchaseRequestCommitteeInfo info = bllPrCommittee.GetPurchaseRequestCommittee(ComSeq);
            txtCommitteeRefno.Text = info.Ref_no.ToString();
            lblCommitteeRefNo.Text = info.Ref_no.ToString();
            rblCommitteeType.SelectedValue = info.InfoType.Seq.ToString();
            if (info.InfoType.Seq == 1)
            {
                panelInternal.Visible = true;
                panelExternal.Visible = false;
                cbCommitteeInternalName.SelectedValue = info.InfoExployee.Seq.ToString();
                cbCommitteeInternalName.Text = info.InfoExployee.Name;
                lblCommitteeInternalName.Text = info.InfoExployee.Name;
            }
            else
            {
                panelInternal.Visible = false;
                panelExternal.Visible = true;
                txtCommitteeExternalName.Text = info.Ex_name;
                txtCommitteeExternalDescr.Text = info.Ex_descr;
            }

            cbCommitteePosition.SelectedValue = info.InfoPosition.Seq.ToString();
            cbCommitteeFunction.SelectedValue = info.InfoFunction.Seq.ToString();
            cmdFac.ViewCommand(panelList_Committee, panelGrid_Committee, panelCommand_Committee);
            cmdFac.SetViewMode(panelInternal);
            cmdFac.SetPanelList(panelInternal, "View");
            cmdFac.SetViewMode(panelExternal);
            cmdFac.SetPanelList(panelExternal, "View");
        }

        protected void Grid_Committee_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Image image = (Image)dataBoundItem["Image"].FindControl("Image1");
                if (dataBoundItem["InfoRecord.InfoStatus.Status"].Text == "W")
                {
                    image.ImageUrl = "../Image/Grid/Update.gif";
                }
                else
                {
                    image.ImageUrl = "../Image/Grid/Cancel.gif";
                }
            }
        }

        protected void LoadValidateCommittee()
        {
            RequiredFieldValidator valCommitteeRefno = new RequiredFieldValidator();
            valCommitteeRefno.ID = "ValtxtCommitteeRefno";
            valCommitteeRefno.ControlToValidate = "txtCommitteeRefno";
            valCommitteeRefno.SetFocusOnError = true;
            valCommitteeRefno.Display = ValidatorDisplay.Dynamic;
            valCommitteeRefno.ErrorMessage = "* กรุณาระบุชุดที่ *";
            panelValtxtCommitteeRefno.Controls.Add(valCommitteeRefno);
            RequiredFieldValidator valCommitteeInternalName = new RequiredFieldValidator();
            valCommitteeInternalName.ID = "ValcbCommitteeInternalName";
            valCommitteeInternalName.ControlToValidate = "cbCommitteeInternalName";
            valCommitteeInternalName.SetFocusOnError = true;
            valCommitteeInternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeInternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValcbCommitteeInternalName.Controls.Add(valCommitteeInternalName);
            RequiredFieldValidator valCommitteeExternalName = new RequiredFieldValidator();
            valCommitteeExternalName.ID = "ValtxtCommitteeExternalName";
            valCommitteeExternalName.ControlToValidate = "txtCommitteeExternalName";
            valCommitteeExternalName.SetFocusOnError = true;
            valCommitteeExternalName.Display = ValidatorDisplay.Dynamic;
            valCommitteeExternalName.ErrorMessage = "* กรุณาระบุชื่อกรรมการ *";
            panelValtxtCommitteeExternalName.Controls.Add(valCommitteeExternalName);
            RequiredFieldValidator valCommitteePosition = new RequiredFieldValidator();
            valCommitteePosition.ID = "ValcbCommitteePosition";
            valCommitteePosition.ControlToValidate = "cbCommitteePosition";
            valCommitteePosition.SetFocusOnError = true;
            valCommitteePosition.Display = ValidatorDisplay.Dynamic;
            valCommitteePosition.ErrorMessage = "* กรุณาระบุตำแหน่งกรรมการ *";
            panelValcbCommitteePosition.Controls.Add(valCommitteePosition);
            RequiredFieldValidator valCommitteeFunction = new RequiredFieldValidator();
            valCommitteeFunction.ID = "ValcbCommitteeFunction";
            valCommitteeFunction.ControlToValidate = "cbCommitteeFunction";
            valCommitteeFunction.SetFocusOnError = true;
            valCommitteeFunction.Display = ValidatorDisplay.Dynamic;
            valCommitteeFunction.ErrorMessage = "* กรุณาระบุหน้าที่กรรมการ *";
            panelValcbCommitteeFunction.Controls.Add(valCommitteeFunction);
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab ผู้ขาย/รับจ้าง

        protected void LoadGridSeller()
        {
            int seq = GetSeq();
            IList<BidderInfo> infoBidder = bllBidder.GetSeller(seq);
            Grid_Seller.DataSource = infoBidder;
            GridGroupByExpression geName = new GridGroupByExpression(Grid_Seller.Columns[1]);
            Grid_Seller.MasterTableView.GroupByExpressions.Add(geName);
            Grid_Seller.DataBind();
        }

        protected void Grid_Seller_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridSeller();
        }

        protected void Delete_Seller_Click(object sender, EventArgs e)
        {
            IList<BidderInfo> infoList = new List<BidderInfo>();
            foreach (GridDataItem data in Grid_Seller.MasterTableView.GetSelectedItems())
            {
                BidderInfo info = new BidderInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllBidder.DeleteFromDB(infoList);
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridSeller();
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab สรุปรายการคัดเลือก

        protected void LoadJudgement()
        {
            int seq = GetSeq();
            JudgementInfo info = bllBidderQuo.GetJudgement(seq);
            lblBudgetAmount.Text = (info.BudgetAmount == null) ? "0" : ((double)info.BudgetAmount).ToString("#,##0.00");
            lblPurchaseAmount.Text = (info.PurchaseAmount == null) ? "0" : ((double)info.PurchaseAmount).ToString("#,##0.00");
            lblResult.Text = info.ResultName;
        }

        protected void LoadGridJudgement()
        {
            int seq = GetSeq();
            IList<BidderQuotationInfo> infoList = bllBidderQuo.GetListJudgement(seq);
            Grid_Judgement.DataSource = infoList;
            Grid_Judgement.MasterTableView.GroupByExpressions.Clear();
            GridGroupByExpression geItemDescr = new GridGroupByExpression(Grid_Judgement.Columns[0]);
            Grid_Judgement.MasterTableView.GroupByExpressions.Add(geItemDescr);
            Grid_Judgement.DataBind();
        }

        protected void Grid_Judgement_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridJudgement();
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab เอกสารแนบ

        protected void LoadGridFile()
        {
            int seq = GetSeq();
            Grid_File.DataSource = bllPprFile.GetDocument(seq, "icm_purchase_request_file", "ICM_PR_SEQ", "icm_pr_file_seq");
            Grid_File.DataBind();

            cmdFac.GridCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void Grid_File_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridFile();
        }

        protected void AddNew_File_Click(object sender, EventArgs e)
        {
            RequiredFieldValidator valFileName = new RequiredFieldValidator();
            valFileName.ID = "ValtxtFileName";
            valFileName.ControlToValidate = "txtFileName";
            valFileName.SetFocusOnError = true;
            valFileName.Display = ValidatorDisplay.Dynamic;
            valFileName.ErrorMessage = "* กรุณาระบุชื่อไฟล์ *";
            panelValtxtFileName.Controls.Add(valFileName);
            RequiredFieldValidator valAttachment = new RequiredFieldValidator();
            valAttachment.ID = "Valattachment";
            valAttachment.ControlToValidate = "attachment";
            valAttachment.SetFocusOnError = true;
            valAttachment.Display = ValidatorDisplay.Dynamic;
            valAttachment.ErrorMessage = "* กรุณาระบุที่อยู่ไฟล์ *";
            panelValattachment.Controls.Add(valAttachment);
            cmdFac.AddNewCommand(panelList_File, panelGrid_File, panelCommand_File);
        }

        protected void AddNewSave_File_Click(object sender, EventArgs e)
        {
            int seq = GetSeq();
            FileInfo infoFile = new FileInfo(hdSourceFile.Value);
            DocumentInfo info = new DocumentInfo();
            RecordInfo infoRecord = new RecordInfo();
            infoRecord.Created_by = Int32.Parse(Session["EmpSeq"].ToString());
            infoRecord.Created_when = DateTime.Now;
            info.File_info = infoFile;
            info.Name = txtFileName.Text;
            info.Dest_path = hdSourceFile.Value;
            info.InfoRecord = infoRecord;

            try
            {
                bllPprFile.InsertFileToDB(info, "ICM_PURCHASE_REQUEST_FILE", "ICM_PR_SEQ", seq);
                LoadGridFile();
            }
            catch
            {
                RadManager1.Alert(SystemInfo._InsertError);
                return;
            }
        }

        protected void Delete_File_Click(object sender, EventArgs e)
        {
            IList<DocumentInfo> infoList = new List<DocumentInfo>();
            foreach (GridDataItem data in Grid_File.MasterTableView.GetSelectedItems())
            {
                DocumentInfo info = new DocumentInfo();
                RecordInfo infoRecord = new RecordInfo();
                info.Seq = Convert.ToInt32(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Seq"]);
                infoRecord.Updated_by = Int32.Parse(Session["EmpSeq"].ToString());
                infoRecord.Updated_when = DateTime.Now;
                info.InfoRecord = infoRecord;
                infoList.Add(info);
            }

            if (infoList.Count == 0)
            {
                RadManager1.Alert(SystemInfo._DeleteNull);
                return;
            }

            try
            {
                bllPprFile.DeleteFileFromDB(infoList, "ICM_PURCHASE_REQUEST_FILE", "ICM_PR_FILE_SEQ");
            }
            catch
            {
                RadManager1.Alert(SystemInfo._DeleteError);
                return;
            }

            LoadGridFile();
        }

        protected void ShowGrid_File_Click(object sender, EventArgs e)
        {
            LoadGridFile();
        }

        protected void OnAjaxUpdate_History(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_History(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_History(string elementID, UpdatePanel panel)
        {
            int seq = GetSeq();
            Session["PrSeq"] = seq;
            Control ctrl = Page.LoadControl("../UserControl/TIP_Purchase_Request_File_History.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region tab ข้อมูลรายงาน

        protected void LoadGrid_Report()
        {
            IList<SysReportInfo> infoList = bllReport.GetReportName("PR_APPROVE");
            Grid_Report.DataSource = infoList;
            Grid_Report.DataBind();
        }

        protected void Grid_Report_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGrid_Report();
        }

        #endregion

        //-----------------------------------------------------------------------------------------------

        #region ความคืบหน้า

        ProgressPurchaseRequestBLL bllPr = new ProgressPurchaseRequestBLL();

        protected void LoadGridApprove()
        {
            int seq = GetSeq();
            IList<PurchaseRequestRouteInfo> InfoPprRouteList = bllPr.GetPurchaseRequestApprove(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridApprove");
            TmpGrid.DataSource = InfoPprRouteList;
            TmpGrid.DataBind();
        }

        protected void LoadGridInform()
        {
            int seq = GetSeq();
            IList<PurchaseRequestRouteInfo> InfoPprRouteList = bllPr.GetPurchaseRequestInform(seq);
            RadGrid TmpGrid2 = (RadGrid)RadPanelBar1.FindItemByValue("Bar1").FindControl("GridInform");
            GridGroupByExpression g;
            TmpGrid2.DataSource = InfoPprRouteList;
            TmpGrid2.MasterTableView.GroupByExpressions.Clear();
            g = new GridGroupByExpression(TmpGrid2.Columns[0]);
            TmpGrid2.MasterTableView.GroupByExpressions.Add(g);

            TmpGrid2.Columns[0].Visible = false;
            TmpGrid2.DataBind();
        }

        protected void LoadGridRequest()
        {
            int seq = GetSeq();
            IList<PurchaseRequestInfo> InfoPpr = bllPr.GetPurchaseRequest(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar2").FindControl("GridRequest");
            TmpGrid.DataSource = InfoPpr;
            TmpGrid.DataBind();
        }

        protected void LoadGridPublishing()
        {
            int seq = GetSeq();
            IList<BidInfo> InfoBid = bllPr.GetBid(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar3").FindControl("GridPublishing");
            TmpGrid.DataSource = InfoBid;
            TmpGrid.DataBind();
        }

        protected void LoadGridCommand()
        {
            int seq = GetSeq();
            IList<PurchaseOrderInfo> InfopurOrder = bllPr.GetPurchaseOrder(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar4").FindControl("GridCommand");
            TmpGrid.DataSource = InfopurOrder;
            TmpGrid.DataBind();
        }

        protected void LoadGridCheck()
        {
            int seq = GetSeq();
            IList<DeliveryNoteInfo> InfoDeliveryNote = bllPr.GetDeliveryNote(seq);
            RadGrid TmpGrid = (RadGrid)RadPanelBar1.FindItemByValue("Bar5").FindControl("GridCheck");
            TmpGrid.DataSource = InfoDeliveryNote;
            TmpGrid.DataBind();
        }

        protected void GridApprove_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridApprove();
        }

        protected void GridHistory_ItemCommand(object source, GridCommandEventArgs e)
        {
            //LoadGridApproveHistory();
        }

        protected void GridInformHis_ItemCommand(object source, GridCommandEventArgs e)
        {
            //LoadGridInformHistory();
        }

        protected void GridInform_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridInform();
        }

        protected void GridRequest_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridRequest();
        }

        protected void GridRequest_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":prr", true);
                    }
                }
            }
        }

        protected void GridPublishing_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridPublishing();
        }

        protected void GridPublishing_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":br", true);
                    }
                }
            }
        }

        protected void GridCommand_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCommand();
        }

        protected void GridCommand_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":por", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":por", true);
                    }
                }
            }
        }

        protected void GridCheck_ItemCommand(object source, GridCommandEventArgs e)
        {
            LoadGridCheck();
        }

        protected void GridCheck_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                Control target = e.Item.FindControl("lkName");
                Control targetRefNo = e.Item.FindControl("lkRefNo");
                if (!Object.Equals(target, null))
                {
                    if (!Object.Equals(this.TipApproveDetail, null))
                    {
                        this.TipApproveDetail.TargetControls.Add(target.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":dnr", true);
                        this.TipApproveDetail.TargetControls.Add(targetRefNo.ClientID, "Item:" + dataBoundItem["Ref_no"].Text + ":dnr", true);
                    }
                }
            }
        }

        protected void OnAjaxUpdate_AppDet(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_AppDet(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_AppDet(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            //if (all_value[0] == "Item")
            //{
            //    Session["Resource_Item_Id"] = all_value[1];
            //    Session["Expense_Id"] = null;
            //}
            //else
            //{
            //    Session["Resource_Item_Id"] = null;
            //    Session["Expense_Id"] = all_value[1];
            //}
            Session["RefNo"] = all_value[1];
            Session["DisType"] = all_value[2];
            Control ctrl = Page.LoadControl("../UserControl/TIP_Approve_Detail.ascx");
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_TipHistoryApprove(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_TipHistoryApprove(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_TipHistoryApprove(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void OnAjaxUpdate_TipHistoryInform(object sender, ToolTipUpdateEventArgs args)
        {
            this.UpdateToolTip_TipHistoryInform(args.Value, args.UpdatePanel);
        }

        private void UpdateToolTip_TipHistoryInform(string elementID, UpdatePanel panel)
        {
            string[] all_value = elementID.Split(new string[] { ":" }, StringSplitOptions.None);
            Session["HisSeq"] = all_value[1];
            Control ctrl;
            if (all_value[0] == "HisApprove")
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryApprove.ascx");
            }
            else
            {
                ctrl = Page.LoadControl("../UserControl/ICM_PPR_RouteHistoryInform.ascx");
            }
            panel.ContentTemplateContainer.Controls.Add(ctrl);
        }

        protected void btnHistory_Click(object sender, EventArgs e)
        {

        }

        protected void btnHistory2_Click(object sender, EventArgs e)
        {

        }

        #endregion

        #region คัดเลือก

        protected void LoadGridSelect()
        {
            if (Grid_Seller.Items.Count > 0)
            {
                Grid_Select.Columns.Clear();
                Grid_Hide_Select.Columns.Clear();
                DataTable dtb = new DataTable();
                DataTable dtbHide = new DataTable();
                int seq = GetSeq();
                IList<BidderInfo> infoBidder = bllBidder.GetSeller(seq);
                if (infoBidder.Count > 0)
                {
                    dtb.Columns.Add("ITEM_DESCR");
                    dtbHide.Columns.Add("ITEM_DESCR");
                    GridTemplateColumn tcc = new GridTemplateColumn();
                    tcc.ItemTemplate = new ItemTemplate.CreateItemTemplateLabel("ITEM_DESCR", "lblItemDescr", GridWidth + 50);
                    tcc.HeaderText = "รายการพัสดุ";
                    tcc.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                    tcc.HeaderStyle.VerticalAlign = VerticalAlign.Top;
                    tcc.ItemStyle.VerticalAlign = VerticalAlign.Top;
                    Grid_Select.Columns.Add(tcc);
                    Grid_Hide_Select.Columns.Add(tcc);
                    for (int i = 0; i < infoBidder.Count; i++)
                    {
                        GridTemplateColumn tc = new GridTemplateColumn();
                        GridTemplateColumn tcHide = new GridTemplateColumn();
                        if (hdSelectStatus.Value.Length > 0)//(isSelectInEditMode)
                        {
                            tc.ItemTemplate = new ItemTemplate.CreateItemTemplateCheckBox(infoBidder[i].InfoMasContact.Name_th, "chk" + infoBidder[i].Seq.ToString(), GridWidth);
                        }
                        else
                        {
                            tc.ItemTemplate = new ItemTemplate.CreateItemTemplateLabel(infoBidder[i].InfoMasContact.Name_th, "lbl" + infoBidder[i].Seq.ToString(), GridWidth);
                        }
                        tcHide.ItemTemplate = new ItemTemplate.CreateItemTemplateLabel(infoBidder[i].InfoMasContact.Name_th, "lbl" + infoBidder[i].Seq.ToString(), GridWidth);
                        tc.HeaderText = (infoBidder[i].InfoVat.Seq == 3
                                ? infoBidder[i].InfoMasContact.Name_th + "</br>" + infoBidder[i].InfoVat.Name
                                : infoBidder[i].InfoMasContact.Name_th + "</br>ราคารวมภาษีมูลค่าเพิ่ม " + infoBidder[i].VatPercent.ToString() + "%");
                        tcHide.HeaderText = (infoBidder[i].InfoVat.Seq == 3
                                ? infoBidder[i].InfoMasContact.Name_th + "</br>" + infoBidder[i].InfoVat.Name
                                : infoBidder[i].InfoMasContact.Name_th + "</br>ราคารวมภาษีมูลค่าเพิ่ม " + infoBidder[i].VatPercent.ToString() + "%");
                        tc.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                        tc.HeaderStyle.VerticalAlign = VerticalAlign.Top;
                        tc.ItemStyle.VerticalAlign = VerticalAlign.Top;
                        Grid_Select.Columns.Add(tc);
                        Grid_Hide_Select.Columns.Add(tcHide);
                        dtb.Columns.Add(infoBidder[i].InfoMasContact.Name_th);
                        dtbHide.Columns.Add(infoBidder[i].InfoMasContact.Name_th);
                    }

                    IList<BidderQuotationInfo> infoItem = bllBidderQuo.GetItemNameFromPurchaseRequest(seq);
                    if (infoItem.Count > 0)
                    {
                        for (int i = 0; i < infoItem.Count; i++)
                        {
                            IList<BidderQuotationInfo> infoQuotation = bllBidderQuo.GetBidderQuotationFromPurchaseRequestItemWithPurchaseRequest(seq, Convert.ToInt32(infoItem[i].InfoPrItem.Seq));
                            if (infoQuotation.Count > 0)
                            {
                                while (infoQuotation.Count > 0)
                                {
                                    DataRow dr = dtb.NewRow();
                                    DataRow drHide = dtbHide.NewRow();
                                    for (int j = 1; j < Grid_Select.Columns.Count; j++)
                                    {
                                        dr["ITEM_DESCR"] = infoItem[i].InfoPrItem.Descr;
                                        drHide["ITEM_DESCR"] = infoItem[i].InfoPrItem.Descr;
                                        for (int k = 0; k < infoQuotation.Count; k++)
                                        {
                                            string contact_name = (infoQuotation[k].InfoBidder.InfoVat.Seq == 3
                                                ? infoQuotation[k].InfoBidder.InfoMasContact.Name_th + "</br>" + infoQuotation[k].InfoBidder.InfoVat.Name
                                                : infoQuotation[k].InfoBidder.InfoMasContact.Name_th + "</br>ราคารวมภาษีมูลค่าเพิ่ม " + infoQuotation[k].InfoBidder.VatPercent.ToString() + "%");
                                            if (contact_name == Grid_Select.Columns[j].HeaderText)
                                            {
                                                if (dr[infoQuotation[k].InfoBidder.InfoMasContact.Name_th].ToString().Length > 0)
                                                {
                                                    continue;
                                                }
                                                else
                                                {
                                                    dr[infoQuotation[k].InfoBidder.InfoMasContact.Name_th] = infoQuotation[k].Descr;
                                                    drHide[infoQuotation[k].InfoBidder.InfoMasContact.Name_th] = infoQuotation[k].Remarks;
                                                    infoQuotation.Remove(infoQuotation[k]);
                                                }
                                            }
                                        }
                                    }
                                    dtb.Rows.Add(dr);
                                    dtbHide.Rows.Add(drHide);
                                }
                            }
                            else
                            {
                                DataRow dr = dtb.NewRow();
                                DataRow drHide = dtbHide.NewRow();
                                dr["ITEM_DESCR"] = infoItem[i].InfoPrItem.Descr;
                                drHide["ITEM_DESCR"] = infoItem[i].InfoPrItem.Descr;
                                dtb.Rows.Add(dr);
                                dtbHide.Rows.Add(drHide);
                            }
                        }
                    }
                }

                Grid_Select.Width = (Grid_Select.Columns.Count + 1) * GridWidth;
                Grid_Select.DataSource = dtb;
                Grid_Select.DataBind();

                Grid_Hide_Select.DataSource = dtbHide;
                Grid_Hide_Select.DataBind();

                string strItemDescr = "";
                for (int i = 0; i < Grid_Select.Items.Count; i++)
                {
                    if (i > 0)
                    {
                        if (strItemDescr == ((Label)Grid_Select.Items[i].FindControl("lblItemDescr")).Text)
                        {
                            strItemDescr = ((Label)Grid_Select.Items[i].FindControl("lblItemDescr")).Text;
                            ((Label)Grid_Select.Items[i].FindControl("lblItemDescr")).Text = "";
                        }
                        else
                            strItemDescr = ((Label)Grid_Select.Items[i].FindControl("lblItemDescr")).Text;
                    }
                    else
                    {
                        strItemDescr = ((Label)Grid_Select.Items[i].FindControl("lblItemDescr")).Text;
                    }
                }

                if (hdSelectStatus.Value.Length > 0)//(isSelectInEditMode)
                {
                    for (int i = 0; i < Grid_Hide_Select.Items.Count; i++)
                    {
                        for (int j = 0; j < infoBidder.Count; j++)
                        {
                            if (((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Length > 0)
                            {
                                string[] astrKeyID = ((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Split(';');
                                if (astrKeyID[1] == SystemInfo._YesStatus)
                                {
                                    ((CheckBox)Grid_Select.Items[i].FindControl("chk" + infoBidder[j].Seq.ToString())).Checked = true;
                                }
                                if (astrKeyID[2] == astrKeyID[3])
                                {
                                    ((CheckBox)Grid_Select.Items[i].FindControl("chk" + infoBidder[j].Seq.ToString())).ForeColor = System.Drawing.Color.Red;
                                }
                            }
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < Grid_Hide_Select.Items.Count; i++)
                    {
                        for (int j = 0; j < infoBidder.Count; j++)
                        {
                            if (((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Length > 0)
                            {
                                string[] astrKeyID = ((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Split(';');
                                if (astrKeyID[1] == SystemInfo._YesStatus)
                                {
                                    ((Label)Grid_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).BackColor = System.Drawing.Color.LightSteelBlue;
                                }
                                if (astrKeyID[2] == astrKeyID[3])
                                {
                                    ((Label)Grid_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).ForeColor = System.Drawing.Color.Red;
                                }
                            }
                        }
                    }
                }
                Grid_Select.Visible = true;
            }
            else
            {
                Grid_Select.Visible = false;
            }
        }

        protected void Edit_Select_Click(object sender, EventArgs e)
        {
            Edit_Select.Visible = false;
            EditSave_Select.Visible = true;
            Cancel_Select.Visible = true;

            hdSelectStatus.Value = "1";
            LoadGridSelect();
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            int seq = GetSeq();
            IList<BidderQuotationInfo> infoList = new List<BidderQuotationInfo>();
            IList<BidderInfo> infoBidder = bllBidder.GetSeller(seq);
			CheckBox chk;

            if (infoBidder.Count > 0)
            {
                for (int i = 0; i < Grid_Hide_Select.Items.Count; i++)
                {
                    for (int j = 0; j < infoBidder.Count; j++)
                    {
                        if (((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Length > 0)
                        {
                            chk = (CheckBox)Grid_Select.Items[i].FindControl("chk" + infoBidder[j].Seq.ToString());
                            if (chk != null)
                            {
                                if (chk.Checked)
                                {
                                    BidderQuotationInfo info = new BidderQuotationInfo();
                                    RecordInfo infoRecord = new RecordInfo();
                                    string[] astrKeyID = ((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Split(';');
                                    string quo_selected = astrKeyID[1];

                                    if (quo_selected != SystemInfo._YesStatus)
                                    {
                                        info.Seq = Convert.ToInt32(astrKeyID[0]);
                                        info.Selected = SystemInfo._YesStatus;
                                        info.SelectedReason = txtSelectReason.Text;
                                        infoRecord.Updated_by = 1;
                                        infoRecord.Updated_when = DateTime.Now;
                                        info.InfoRecord = infoRecord;
                                        infoList.Add(info);
                                    }
                                }
                                else
                                {
                                    BidderQuotationInfo info = new BidderQuotationInfo();
                                    RecordInfo infoRecord = new RecordInfo();
                                    string[] astrKeyID = ((Label)Grid_Hide_Select.Items[i].FindControl("lbl" + infoBidder[j].Seq.ToString())).Text.Split(';');
                                    string quo_selected = astrKeyID[1];

                                    if (quo_selected != SystemInfo._NoStatus)
                                    {
                                        info.Seq = Convert.ToInt32(astrKeyID[0]);
                                        info.Selected = SystemInfo._NoStatus;
                                        info.SelectedReason = txtSelectReason.Text;
                                        infoRecord.Updated_by = 1;
                                        infoRecord.Updated_when = DateTime.Now;
                                        info.InfoRecord = infoRecord;
                                        infoList.Add(info);
                                    }
                                }
                            }
                        }
                    }
                }
                if (infoList.Count > 0)
                {
                    bllBidderQuo.SelectedBidderQuotation(infoList);
                }
                Cancel_Select_Click(null, null);
            }
        }

        protected void Cancel_Select_Click(object sender, EventArgs e)
        {
            Edit_Select.Visible = true;
            EditSave_Select.Visible = false;
            Cancel_Select.Visible = false;

            hdSelectStatus.Value = "";
            LoadGridSelect();
        }

        #endregion
    }
}
